#encoding:utf8
import pymongo
from functools import wraps
import logging


def chk_collection(method):
	@wraps(method)
	def wrapper(self, *args, **kwargs):
		if self._enable_collection():
			return
		return method(self, *args, **kwargs)

	return wrapper

class DbMgr():
	
	_conn = None
	_db   = None

	_cltname = None

	def __init__(self, host , port):
		HOST = host 
		PORT = port
		logging.info("Init DataBase...")
		try:
			if self._conn == None:
				self._conn = pymongo.MongoClient(host = HOST , port = PORT)
				logging.info ("DB _conn to HOST %s:%s success!"%(str(HOST), str(PORT)))
			else:
				logging.info ("DB _conn inited!")
		except:
			error ("DB _conn failed!")

	def _enable_collection(self):
		if not self._cltname:
			logging.error("No collection choosed!")
			return True



	def use(self , dbname):
		logging.info("DB use db--> %s"%dbname)
		self._db = self._conn[dbname]

	def use_collection(self , collectionname):
		logging.info("DB use collection--> %s" % collectionname)
		olddb = self._db
		self._db = olddb[collectionname]
		self._cltname = collectionname
		return self._db

	@chk_collection
	def insert(self , doc):
		# try:
		# logging.info("DB inser one doc")
		self._db.insert(doc)
		# except:
		# error("DB insert failed")

	@chk_collection
	def find_one(self , resuledoc):
		try:
			ret = self._db.find_one(resuledoc)
			return ret
		except:
			error("DB find failed")

	@chk_collection
	def remove(self, resuledoc):
		self._db.remove(resuledoc)

	@chk_collection
	def get_course(self):
		return self._db.find()

	@chk_collection
	def get_db(self):
		return self._db

	@chk_collection
	def update(self, finddic, setdic):
		self._db.update(finddic, setdic)

	def close(self):
		self._conn.close()